package com.mf.service.impl.basic;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.mf.constant.ConstantPermission;
import com.mf.entity.dto.basic.DtoPermission;
import com.mf.entity.dto.basic.DtoUser;
import com.mf.entity.dto.basic.webPage.DtoWebMenu;
import com.mf.entity.req.basic.ReqLogin;
import com.mf.entity.vo.basic.VoLogin;
import com.mf.exception.GraceException;
import com.mf.service.basic.ServiceAuth;
import com.mf.service.basic.ServicePermission;
import com.mf.service.basic.ServiceRole;
import com.mf.service.basic.ServiceUser;
import com.mf.service.basic.webPage.ServiceWebMenu;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: lmf
 * @Create: 2025/5/8 13:21
 * @module
 */
@Service
public class ImplServiceAuth implements ServiceAuth {

    @Resource
    private ServiceUser serviceUser;

    @Resource
    private ServiceRole serviceRole;

    @Resource
    private ServicePermission servicePermission;


    @Resource
    private ServiceWebMenu servicewebMenu;

    /**
     * 登录
     */
    @Override
    public VoLogin login(ReqLogin reqLogin) {
        DtoUser dtoUser = serviceUser.findByAccount(reqLogin.getUsername());
        GraceException.display(ObjectUtils.isEmpty(dtoUser), "用户不存在");

        dtoUser.setPassword("");
        // 登录
        StpUtil.login(dtoUser.getId());

        // 获取用户角色
        List<Integer> roleIds = serviceRole.listByUserId(dtoUser.getId());

        List<String> permissions;
        // 根据角色Id集合查询权限
        if (ConstantPermission.ADMIN_ID.equals(dtoUser.getId())) {
            // 管理员所有权限
            permissions = servicePermission.list().stream().map(DtoPermission::getPermName).toList();
        } else {
            // 根据角色Id集合查询权限
            permissions = servicePermission.listByRoleId(roleIds);
        }
        List<DtoWebMenu> dtoWebMenus = servicewebMenu.listTreeByPermission(permissions);

        // 缓存用户
        SaSession session = StpUtil.getSession();
        session.set(SaSession.USER, dtoUser)
                .set(SaSession.ROLE_LIST, roleIds.stream().map(String::valueOf).toList())
                .set(SaSession.PERMISSION_LIST, permissions)
                // 有递归嵌套不使用 JSON.toJSONString 会导致查询的时候 dtoWebMenus children内容丢失
                .set(ConstantPermission.FRONT_MENU, JSON.toJSONString(dtoWebMenus))
        ;

        return VoLogin.builder().token(StpUtil.getTokenValue())
                .user(dtoUser)
                .build();
    }

}
